package cn.edu.nhic.nhcarsb.controller.admin;

import cn.edu.nhic.nhcarsb.controller.BaseController;
import cn.edu.nhic.nhcarsb.entity.Base;
import cn.edu.nhic.nhcarsb.entity.Category;
import cn.edu.nhic.nhcarsb.entity.R;
import cn.edu.nhic.nhcarsb.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController("adminCategoryController")
@RequestMapping("/admin/category")
@Api(value = "后台管理-category", tags = "后台管理-category")
public class CategoryController extends BaseController {
    @Autowired
    private CategoryService categoryService;
    @GetMapping("/{cid}")
    public R get(@PathVariable Integer cid){
        Category category = categoryService.getById(cid);
        return R.success(category);
    }

    @GetMapping("/{page}/{pageSize}")
    public R list(@PathVariable Integer page, @PathVariable Integer pageSize,
                  @RequestParam(value = "key", defaultValue = "") String key) {
        Page<Category> pageInfo = new Page<Category>(page, pageSize);
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(!ObjectUtils.isEmpty(key), Category::getCname, key);
        Page<Category> categoryPage = categoryService.page(pageInfo, lambdaQueryWrapper);
        return R.success(categoryPage);
    }
    @DeleteMapping("/{cid}")
    public R delete(@PathVariable Integer cid){
        boolean result = categoryService.removeById(cid);
        return result?R.success("删除成功！"):R.error("删除失败！");
    }
    @PostMapping
    public R save(@RequestBody @Validated({Category.Save.class}) Category category){
        boolean result = categoryService.save(category);
        return result?R.success("添加成功！"):R.error("添加失败！");
    }
    @PutMapping
    public R update(@RequestBody @Validated({Category.Update.class}) Category category){
        boolean result = categoryService.save(category);
        return result?R.success("更新成功！"):R.error("更新失败！");
    }
}
